package com.anuo.app.study.studydesignpatterns;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.text.MessageFormat;

/**
 * java 回调
 * 参考: http://java-design-patterns.com/patterns/callback/
 * 应用场景: when some arbitrary synchronous or asynchronous action must be performed after execution of some defined activity.
 * 好处: 方法调用更加灵活, 如下实例
*       源头声明一个回调方法, 并接收源头的参数, 然后在后面一连串方法调用完成后, 最后再回过头来调用
 *      这个回调方法, 如果不用回调, 那你最后调用这个方法的时候需要自己去获取age 麻烦
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:spring/spring-context.xml"})

public class StudyCallback {

    @Test
    public void studyCallback() {

        Task task = new SimpleTask();
        final int age = 27;
        String msg = MessageFormat
                .format("welcome back,I am done now. my age is {0}"
                , age);

        Callback callback = new Callback() {
            @Override
            public void Call() {
                System.out.println(msg);
            }

        };
        task.executeWith(callback);
    }


    private abstract class Task {
        public void executeWith(Callback callback) {
            execute();
            if (callback != null) {
                callback.Call();
            }
        }

        public abstract void execute();
    }

    private class SimpleTask extends Task {
        @Override
        public void execute() {
            System.out.println("Perform some important activity and after call the callback method.");
        }
    }

    private interface Callback {
        void Call();
    }
}

